/**
 * Copyright 2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef MINDSPORE_NNACL_FP32_BCE_WITH_LOGITS_LOSS_AVX512_H_
#define MINDSPORE_NNACL_FP32_BCE_WITH_LOGITS_LOSS_AVX512_H_

#include "nnacl/intrinsics/ms_simd_instructions.h"
#include "nnacl/intrinsics/ms_simd_avx512_instructions.h"

#ifdef __cplusplus
extern "C" {
#endif
#pragma GCC push_options
#pragma GCC target("avx512f")
#define MS_SIMD_INSTRUCTION MS_SIMD_AVX512_INSTRUCTION
#define BLOCK_NUM 16
#define MS_SIMD_AVX512

static inline int BCEWithLogitLossAVX512(int index, const float *logits, const float *label,
    const float *weight, const float *pos_weight, int length, bool reduction, float *output,
    float *reduction_sum) {
    SIMD_F32 zero = SIMD_SET0_F32;
    SIMD_F32 ones = SIMD_MOV_F32(1.0f);
    SIMD_F32 middle_output = SIMD_SET0_F32;
    for (int block_max_size = length - BLOCK_NUM + 1; index < block_max_size; index += BLOCK_NUM) {
      SIMD_F32 logits_tmp = SIMD_LD_F32(logits + index);
      SIMD_F32 label_tmp = SIMD_LD_F32(label + index);
      SIMD_F32 weight_tmp = SIMD_LD_F32(weight + index);
      SIMD_F32 pos_weight_tmp = SIMD_LD_F32(pos_weight + index);
      SIMD_F32 neg_logits_tmp = SIMD_SUB_F32(zero, logits_tmp);
      SIMD_F32 max_value = neg_logits_tmp;
      max_value = SIMD_MAX_F32(max_value, zero);
      SIMD_F32 neg_max_value = SIMD_SUB_F32(zero, max_value);
      SIMD_F32 log_weight = SIMD_ADD_F32(SIMD_MUL_F32(SIMD_SUB_F32(pos_weight_tmp, ones), label_tmp), ones);
      SIMD_F32 log_exp_value =
        SIMD_LOG_F32(SIMD_ADD_F32(SIMD_HEXP_F32(neg_max_value), SIMD_HEXP_F32(SIMD_SUB_F32(neg_logits_tmp, max_value))));
      SIMD_F32 loss = SIMD_ADD_F32(SIMD_MUL_F32(SIMD_SUB_F32(ones, label_tmp), logits_tmp),
                                    SIMD_MUL_F32(log_weight, SIMD_ADD_F32(log_exp_value, max_value)));
      if (reduction) {
        middle_output = SIMD_FMADD_F32(loss, weight_tmp, middle_output);
      } else {
        SIMD_ST_F32(output + index, SIMD_MUL_F32(loss, weight_tmp));
      }
    }
    if (reduction) {
      *reduction_sum += SIMD_GET_SUM_F32(middle_output);
    }
    return index;
}
#undef MS_SIMD_INSTRUCTION
#undef BLOCK_NUM
#pragma GCC pop_options
#undef MS_SIMD_AVX512
#ifdef __cplusplus
}
#endif
#endif
